import { useEventListener, useMount, useRequest } from 'ahooks'
import { useNavigate } from 'react-router-dom'
import sha256 from 'crypto-js/sha256'
import { login } from '@/apis'

import { Typography, Form, Input, Button } from 'antd'

import { Token, UserInfo } from '@/apis/config'

const { Title } = Typography

const Login = () => {
  const navigate = useNavigate()
  const [form] = Form.useForm()

  const { run } = useRequest(
    values => {
      return login({
        account: values.username,
        // pwd: isOperator ? sha256(values.password).toString() : btoa(values.password)
        pwd: true ? sha256(values.password).toString() : btoa(values.password)
      })
    },
    {
      manual: true,
      throttleWait: 500,
      onSuccess: res => {
        if (!res) return

        Token.set(res.token)
        UserInfo.set({
          name: res.name
        })
        navigate('/')
      }
    }
  )

  useEventListener('keyup', e => {
    if (['NumpadEnter', 'Enter'].includes(e.code)) {
      form.submit()
    }
  })

  useMount(() => {
    if (Token.get()) {
      navigate('/')
    }
  })

  return (
    <div className="self-center -translate-y-50 w-[480px] bg-white shadow rounded-12 pt-44 pb-60 px-70">
      <Title className="text-center" level={2}>
        智脑管理系统
      </Title>

      <Form form={form} className="mt-48" onFinish={run}>
        <Form.Item name="username" rules={[{ required: true, message: '请输入账号' }]}>
          <Input className="leading-[38px]" placeholder="请输入账号" />
        </Form.Item>

        <Form.Item name="password" rules={[{ required: true, message: '请输入密码' }]}>
          <Input.Password className="leading-[38px]" placeholder="请输入密码" />
        </Form.Item>

        <Button className="mt-16 h-48" type="primary" htmlType="submit" block>
          登录
        </Button>
      </Form>
    </div>
  )
}

export default Login
